export function unifyNumber(num) {
  if (num === '') {
    return 0;
  } else {
    const handleNum = parseFloat(num);
    const isToFixed = handleNum.toString().includes('.') && handleNum.toString().split('.')[1].length > 2;
    if (isToFixed) {
      return handleNum.toFixed(2);
    } else {
      return handleNum;
    }
  }
}

export const formatName = (list, code, key, valueKey) => {
  let name = '';
  try {
    for (let i = 0; i < list.length; i++) {
      if (list[i][key] == code) {
        name = list[i][valueKey];
        return name;
      }
      if (list[i].children) {
        formatName(list[i].children, code, key, valueKey);
      }
      if (list[i].child) {
        formatName(list[i].child, code, key, valueKey);
      }
    }
  } catch (e) {
    console.error(e);
  }
};

/**
 *  @param num1加数1
 *  @param num2加数2
 */
export function numAdd(num1, num2) {
  let baseNum, baseNum1, baseNum2;
  try {
    baseNum1 = num1.toString().split('.')[1].length;
  } catch (e) {
    baseNum1 = 0;
  }
  try {
    baseNum2 = num2.toString().split('.')[1].length;
  } catch (e) {
    baseNum2 = 0;
  }
  baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
  return (num1 * baseNum + num2 * baseNum) / baseNum;
}

/**
 * 两个数相减
 */
export function numSub(a, b, precision = 10) {
  const factor = Math.pow(10, precision); // 放大倍数（如 10^10）
  const scaledA = Math.round(a * factor); // 放大后转为整数
  const scaledB = Math.round(b * factor);
  const result = (scaledA - scaledB) / factor; // 缩小回原比例
  return result;
}

export function numMulti(num1, num2) {
  let baseNum = 0;
  try {
    baseNum += num1.toString().split('.')[1].length;
  } catch (e) {}
  try {
    baseNum += num2.toString().split('.')[1].length;
  } catch (e) {}
  return (Number(num1.toString().replace('.', '')) * Number(num2.toString().replace('.', ''))) / Math.pow(10, baseNum);
}

export function numDiv(num1, num2) {
  let baseNum1 = 0,
    baseNum2 = 0;
  let baseNum3, baseNum4;
  try {
    baseNum1 = num1.toString().split('.')[1].length;
  } catch (e) {
    baseNum1 = 0;
  }
  try {
    baseNum2 = num2.toString().split('.')[1].length;
  } catch (e) {
    baseNum2 = 0;
  }
  baseNum3 = Number(num1.toString().replace('.', ''));
  baseNum4 = Number(num2.toString().replace('.', ''));
  return (baseNum3 / baseNum4) * Math.pow(10, baseNum2 - baseNum1);
}
